<template>
	<div class="editor-bar-wrap">
		<div ref="toolbar" class="toolbar"></div>
		<div ref="editor" class="text"></div>
	</div>
</template>

<script>
	
	import { GET_POLICY } from '@/api/crm'
	
	import E from 'wangeditor'
	import Xss from 'xss';

	export default {
		name: 'Editorbar',
		data() {
			return {
				editor: null,
				info_: null,
				file_index: 0
			}
		},
		model: {
			prop: 'value',
			event: 'change'
		},
		props: {
			value: {
				type: String,
				default: ''
			},
			isClear: {
				type: Boolean,
				default: false,
			}
		},
		watch: {
			isClear(val) {
				// 触发清除文本域内容
				if(val) {
					this.editor.txt.clear()
					this.info_ = null
				}
			},
			// 使用v-model时，设置初始值
			value(val) {
				console.log(val, 899999)
				this.editor.txt.html(val)
			}
		},
		mounted() {
			this.setEditor()
		},
		methods: {
			// 初始化wangeditor
			setEditor() {
				this.editor = new E(this.$refs.toolbar, this.$refs.editor);
				this.editor.customConfig.customUploadImg = (files, insert) => { // customUploadImg包含参数(files, insert) 
					this.recurrenceUpload(files, insert)
				}
				this.editor.customConfig.menus = [
					'head', // 标题
					'bold', // 粗体
					'fontSize', // 字号
					'fontName', // 字体
					'italic', // 斜体
					'underline', // 下划线
					'strikeThrough', // 删除线
					'foreColor', // 文字颜色
					'backColor', // 背景色
					'link', // 链接
					'list', // 列表
					'jusitify', // 对齐方式
					'quote', // 引用
					'emoticon', // 表情
					'image', // 图片
					'table', // 表格
					'video', // 视频
					'code', // 代码
					'undo', // 撤销
					'redo', // 重复
				]
				this.editor.customConfig.onchange = (html) => {
					this.info_ = Xss(html) // 绑定当前逐渐地值
					this.$emit('change', this.info_) //将内容同步到父组件中
				}
				// 创建富文本编辑器
				this.editor.create()
			},
			// 通过GET_POLICY获取上传地址信息
			async getUploadInfo(base64Img) { //图片上传
				let file = this.dataURItoFile(base64Img)
				let url = ''
				const fileType = file.type.split('/')[1]
				const typeArray = ['gif', 'jpg', 'jpeg', 'png']
				if(!typeArray.includes(fileType)) {
					this.$message({
						message: '图片格式仅支持gif, jpg, jpeg,png',
						type: 'warning'
					});
					return false;
				}
				await this.$http.get(GET_POLICY)
					.then(async(res) => {
						const fd = new FormData()
						const {
							accessid,
							// host,
							policy,
							signature,
							dir,
							expire
						} = res.data.data
						fd.append('OSSAccessKeyId', accessid)
						fd.append('policy', policy)
						fd.append('signature', signature)
						fd.append('key', dir + expire)
						fd.append('success_action_status', 200)
						fd.append('file', file, expire)
						url = await this.uploadImg(fd, res.data.data)
					})
				return(url)
			},
			// 上传图片的action
			uploadImg(fd, data) {
				const {
					// accessid,
					host,
					// policy,
					// signature,
					dir,
					expire
				} = data
				return new Promise(function(resolve, reject) {
					let url = 'null.jpg'
					const xhr = new XMLHttpRequest()
					if(xhr) {
						xhr.open('post', host, true)
						xhr.onload = () => {
							if(xhr.status === 200) {
								url = host + '/' + dir + expire
								resolve(url)
							}
						}
						xhr.onerror = () => {
							reject("Unable to load RSS")
						}
						xhr.send(fd)
					}
				})
			},
			// 递归上传，目前间隔一秒
			recurrenceUpload(files) {
				let that = this
				let index = that.file_index
				if(index > files.length - 1) {
					that.file_index = 0
				} else {
					// 也可以在这里过滤图片大小
					that.readBlobAsDataURL(files[index], (data_url) => {
						// console.log(data_url)
						that.getUploadInfo(data_url).then((res) => {
							that.editor.cmd.do('insertHTML', '<img src="' + res + '" style="max-width:100%;"/>');
							index++
							that.file_index = index
							setTimeout(() => {
								that.recurrenceUpload(files)
							}, 1000)
						})
					})
				}
			},
			// dataUrl 转换成 file base64 => file 
			dataURItoFile(dataurl) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while(n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			// File对象转换为dataURL、Blob对象转换为dataURL
			readBlobAsDataURL(blob, callback) {
				var a = new FileReader();
				a.onload = function(e) {
					callback(e.target.result);
				};
				a.readAsDataURL(blob);
			}
		}
	}
</script>

<style lang="scss">
	.editor-bar-wrap {
		.w-e-text-container,
		.w-e-menu {
			z-index: 999 !important;
		}
		.toolbar {
			border: 1px solid #ccc;
		}
		.text {
			border: 1px solid #ccc;
			height: 500px;
		}
	}
</style>